const BaseController = require('./base_controller.js');
const DeviceManagementService = require('../service/device_management_service.js');

class DeviceManagementController extends BaseController {

  /**
   * 添加设备
   */
  async addDevice() {
    this.ensureAuthenticatedForWrite();

    // 数据校验
    let rules = {
      name: 'required|string|min:1|max:50|name=设备名称',
      type: 'required|string|in:dryer,bath,grooming,door|name=设备类型',
      category: 'required|string|in:grooming,bath,foster,access|name=设备分类',
      location: 'required|string|min:1|max:100|name=设备位置',
      price: 'required|int|min:1|name=基础价格',
      mqttTopic: 'required|string|min:1|max:200|name=MQTT主题',
      storeId: 'required|string|name=门店ID',
    };

    let input = this.validateData(rules);

    const service = new DeviceManagementService();
    return await service.addDevice(input);
  }

  /**
   * 删除设备
   */
  async deleteDevice() {
    this.ensureAuthenticatedForWrite();

    // 数据校验
    let rules = {
      deviceId: 'required|string|name=设备ID',
    };

    let input = this.validateData(rules);

    const service = new DeviceManagementService();
    await service.deleteDevice(input.deviceId);
    return { success: true, message: '设备删除成功' };
  }

  /**
   * 更新设备
   */
  async updateDevice() {
    this.ensureAuthenticatedForWrite();

    // 数据校验
    let rules = {
      deviceId: 'required|string|name=设备ID',
      name: 'string|min:1|max:50|name=设备名称',
      type: 'string|in:dryer,bath,grooming,door|name=设备类型',
      category: 'string|in:grooming,bath,foster,access|name=设备分类',
      location: 'string|min:1|max:100|name=设备位置',
      price: 'int|min:1|name=基础价格',
      mqttTopic: 'string|min:1|max:200|name=MQTT主题',
      status: 'int|in:0,1,2|name=设备状态',
    };

    let input = this.validateData(rules);

    const service = new DeviceManagementService();
    return await service.updateDevice(input.deviceId, input);
  }

  /**
   * 获取设备列表
   */
  async getDeviceList() {
    // 数据校验 - 允许所有已认证用户查看设备列表
    let rules = {
      page: 'int|min:1|default=1|name=页码',
      size: 'int|min:1|max:200|default=20|name=每页数量',
      storeId: 'string|name=门店ID',
      type: 'string|name=设备类型',
      status: 'int|name=设备状态',
      search: 'string|max:50|name=搜索关键词',
    };

    let input = this.validateData(rules);

    const service = new DeviceManagementService();
    const result = await service.getDeviceList(input);
    return result;
  }
}

module.exports = DeviceManagementController;
